/*
 This file 'DatePicker' is part of Firebird Integrated Solution 1.0

 Copyright (c) 2014 Lincong

 Contact:  
 Email: lincong1987@gmail.com

 QQ: 159257119

 See Usage at http://www.jplatformx.com/firebird

 Create date: 2014-06-19 16:06
 */
define(function (require, exports, module) {


	require("Firebird.ui.Component");
	require("../datepicker/WdatePicker");
	require("Firebird.ui.TextField");

	var moment = require("../moment/moment");

	// 适配器
	var datepicterAdatper = window.$dp;

	/**
	 * 日期/时间 选择器
	 * @class Firebird.ui.DatePicker
	 * @see My97DatePicker
	 * @link [http://www.my97.net/dp/demo/index.htm]
	 *
	 * 日期格式表
	 * 格式    说明
	 * y    将年份表示为最多两位数字。如果年份多于两位数，则结果中仅显示两位低位数。
	 * yy    同上，如果小于两位数，前面补零。
	 * yyy    将年份表示为三位数字。如果少于三位数，前面补零。
	 * yyyy    将年份表示为四位数字。如果少于四位数，前面补零。
	 * M    将月份表示为从 1 至 12 的数字
	 * MM    同上，如果小于两位数，前面补零。
	 * MMM    返回月份的缩写 一月 至 十二月 (英文状态下 Jan to Dec) 。
	 * MMMM    返回月份的全称 一月 至 十二月 (英文状态下 January to December) 。
	 * d    将月中日期表示为从 1 至 31 的数字。
	 * dd    同上，如果小于两位数，前面补零。
	 * H    将小时表示为从 0 至 23 的数字。
	 * HH    同上，如果小于两位数，前面补零。
	 * m    将分钟表示为从 0 至 59 的数字。
	 * mm    同上，如果小于两位数，前面补零。
	 * s    将秒表示为从 0 至 59 的数字。
	 * ss    同上，如果小于两位数，前面补零。
	 * w    返回星期对应的数字 0 (星期天) - 6 (星期六) 。
	 * D    返回星期的缩写 一 至 六 (英文状态下 Sun to Sat) 。
	 * DD    返回星期的全称 星期一 至 星期六 (英文状态下 Sunday to Saturday) 。
	 * W    返回周对应的数字 (1 - 53) 。
	 * WW    同上，如果小于两位数，前面补零 (01 - 53) 。
	 *
	 * 示例
	 * 格式字符串    值
	 * yyyy-MM-dd HH:mm:ss    2008-03-12 19:20:00
	 * yy年M月    08年3月
	 * yyyyMMdd    20080312
	 * 今天是:yyyy年M年d HH时mm分    今天是:2008年3月12日 19时20分
	 * H:m:s    19:20:0
	 * y年    8年
	 * MMMM d, yyyy    三月 12, 2008
	 *
	 */
	Firebird.define("Firebird.ui.DatePicker", {
		extend: "Firebird.ui.TextField",
		statics: {
			_uuid: 1,
			uuid: function () {
				return this._uuid++;
			},
			/**
			 * 属性适配器
			 * @param $component
			 * @returns {{}}
			 */
			attrs: function ($component) {
				return $.extend({}, {
					renderTo: $component.get(0),
					instanceId: $component.attr("fb-instance") || $component.attr("name") || $component.attr("id") || ("datepicker_" + Firebird.ui.DatePicker.uuid()),
					width: $component.attr("fb-width"),
					placeholder: $component.attr("fb-placeholder") || $component.attr("placeholder") || "",
					trigger: $component.attr("fb-trigger"),

					limit: Firebird.ui.Component.eval($component.attr("fb-limit")),
					on: Firebird.ui.Component.eval($component.attr("fb-on")),

					focus: Firebird.ui.Component.eval($component.attr("fb-focus")),
					disabled: Firebird.ui.Component.eval($component.attr("fb-disabled") || $component.prop("disabled")),
					readonly: Firebird.ui.Component.eval($component.attr("fb-readonly") || $component.prop("readonly")),
					hidden: Firebird.ui.Component.eval($component.attr("fb-hidden") || $component.is("[type=hidden]")),

					doubleCalendar: Firebird.ui.Component.eval($component.attr("fb-doubleCalendar")),
					position: Firebird.ui.Component.eval($component.attr("fb-position")) || {},
					//inFormat: $component.attr("fb-inFormat"),
					//outFormat: $component.attr("fb-outFormat"),
					dateFmt: $component.attr("fb-dateFmt"),
					showDateFmt: $component.attr("fb-showDateFmt") || $component.attr("fb-dateFmt") || "",
					realDateFmt: $component.attr("fb-realDateFmt"),
					realTimeFmt: $component.attr("fb-realTimeFmt"),
					realFullFmt: $component.attr("fb-realFullFmt"),
					minDate: $component.attr("fb-minDate"),
					maxDate: $component.attr("fb-maxDate"),
					startDate: $component.attr("fb-startDate"),

					errDealMode: Firebird.ui.Component.eval($component.attr("fb-errDealMode")) || 0,

					realDate: Firebird.ui.Component.eval($component.attr("fb-realDate") || true),

					options: Firebird.ui.Component.eval($component.attr("fb-options"))

				});
			}
		},
		config: {
			renderTo: null,
			instanceId: null,
			width: 222,
			placeholder: null,
			trigger: "focus click",
			adapter: null,

			disabled: false,
			focus: false,
			readonly: true,
			hidden: false,

			//inFormat: null,
			//outFormat: null,

			/**
			 * 是否是双月模式,如果该属性为true,则弹出同时显示2个月的日期框
			 */
			doubleCalendar: false,
			enableKeyboard: true,
			enableInputMask: true,
			autoUpdateOnChanged: null,
			/**
			 * 日期选择框显示位置
			 * 注意:坐标单位是px,是相对当前框架坐标(不受滚动条影响),默认情况下系统根据页面大小自动选择
			 * 如:
			 * {left:100,top:50}表示固定坐标[100,50]
			 * {top:50}表示横坐标自动生成,纵坐标指定为 50
			 * {left:100}表示纵坐标自动生成,横坐标指定为 100
			 * 请参考示例
			 */
			position: {},
			dateFmt: "yyyy-MM-dd",
			showDateFmt: "yyyy-MM-dd",
			realDateFmt: "yyyy-MM-dd",
			realTimeFmt: " HH:mm:ss",
			realFullFmt: "%Date %Time",
			minDate: "1900-01-01 00:00:00",
			maxDate: "2099-12-31 23:59:59",
			startDate: "",

			alwaysUseStartDate: false,
			yearOffset: 1911,
			firstDayOfWeek: 0,
			isShowWeek: false,
			highLineWeekDay: true,

			isShowClear: true,
			isShowToday: true,
			isShowOK: true,
			isShowOthers: true,

			readOnly: false,
			errDealMode: -1,
			autoPickDate: null,
			qsEnabled: true,
			autoShowQS: false,
			opposite: false,
			hmsMenuCfg: {H: [1, 6], m: [5, 6], s: [15, 4]},
			specialDates: null,
			specialDays: null,
			disabledDates: null,
			disabledDays: null,

			onpicking: null,
			onpicked: null,
			onclearing: null,
			oncleared: null,
			ychanging: null,
			ychanged: null,
			Mchanging: null,
			Mchanged: null,
			dchanging: null,
			dchanged: null,
			Hchanging: null,
			Hchanged: null,
			mchanging: null,
			mchanged: null,
			schanging: null,
			schanged: null,
			eCont: null,

			realDate: true,

			options: {},

			//vel: null,
			elProp: "",
			errMsg: ""

		},

		isPlaceholderSupport: "placeholder" in document.createElement("input"),

		wrapCls: "fb-ui-datepicker",

		_init: function () {
			var me = this;

			me.genId = Firebird.Model.getGenId();

			me.instance = $(me.getRenderTo()).addClass(this.wrapCls + "-input").data({
				instance: me,
				xtype: "datepicker"
			});

			this.render();

			me.options = $.extend({}, me.initialConfig, {
				el: me.instance.get(0)
			}, me.getOptions(), {
				vel: me.genId + "-vel"
			});

			var _onpicked = me.options.onpicked || function () {
				};

			var _onclearing = me.options.onclearing || function () {
				};
			me.options.onpicked = function (arg) {
				_onpicked.apply(this, [arg[0]]);
				me.instance.trigger("onPicked");
			};

			me.options.onclearing = function (arg) {
				_onclearing.apply(this, [arg[0]]);
				me.instance.trigger("onClearing");
			};

			me.on(me.getTrigger(), function () {
				window.WdatePicker.apply(me.instance.get(0), [me.options]);
			});

			this.setReadonly(this.getReadonly());
			this.setDisabled(this.getDisabled());
			this.setWidth(this.getWidth());
			this.setFocus(this.getFocus());
			this.setHidden(this.getHidden());

			me._setValue(me.instance.attr("fb-value") || me.instance.val());

			if (!me.isPlaceholderSupport) {
				this.setPlaceholder(this.getPlaceholder());
			} else {
				this.instance.attr("placeholder", this.getPlaceholder());
			}

			this.bindPlaceholder();
		},
		render: function () {
			var me = this;
			me.instance.wrap($("<span class='" + this.wrapCls + "'></span>"));
			var wrapper = this.wrapper = me.instance.parent();

			var $placeholder = me.$placeholder = $("<span class='" + this.wrapCls + "-placeholder'></span>");
			me.instance.before($placeholder);

			me.$vel = $("<input type='hidden' id='" + me.genId + "-vel' />");
			me.instance.after(me.$vel);

			me.wrapper.data("instance", me);

			me.instance.on("focus", function () {
				$_$dp && $_$dp.setShowStatus(true);
				wrapper.addClass(me.wrapCls + "-focus");
				setTimeout(function () {
					me.bindPlaceholder();
					me.instance.trigger("focusout");
				}, 0);
				me.instance.trigger("focusin");
			}).on("blur", function () {
				wrapper.removeClass(me.wrapCls + "-focus");
				me.bindPlaceholder();
				me.asyncValue();
				me.instance.trigger("focusout");
			}).on("keydown keyup keypress change", function (e) {
				// me.bindPlaceholder();
				// e.preventDefault();
				// me.asyncValue();
				//return false;
			});

			this.wrapper.on("mouseover", function () {
				me.wrapper.addClass(me.wrapCls + "-hover");
				if (me.wrapper.hasClass(me.wrapCls + "-invalid")) {
					me.instance.trigger("showErrorMessage");
				}
			});

			this.wrapper.on("mouseout", function () {
				me.wrapper.removeClass(me.wrapCls + "-hover");
				if (me.wrapper.hasClass(me.wrapCls + "-invalid")) {
					me.instance.trigger("hideErrorMessage");
				}
			});

			this.$placeholder.on("click", function (e) {
				me.setFocus(true);
				e.preventDefault();
			});
		},

		setValue: function (value) {
			this._setValue(value);
			this.bindPlaceholder();
		},
		_setValue: function (value) {
			value = this.inFilter(value);

			this.instance.trigger("onSetValue", {value: value});

			if (value == "") {
				return this;
			}

			// 与moment的映射
			var momentMap = {
				yyyy: "YYYY",
				dd: "DD",
				d: "D"
			};
			

			var opts = this.options;

			if (this.getDateFmt()) {
				var momentFmt =  this.getDateFmt();
				for (var key in momentMap) {
					momentFmt = momentFmt.replace(new RegExp(key, "g"), momentMap[key]);
				}
				this.instance.val(moment(value == "" ? (firebird.date.format(new Date())) : value, momentFmt).format(momentFmt));
			}

			// 解析时间
			var velFmt = opts.realDateFmt || "yyyyMMdd";
			if (opts.realTimeFmt) {
				velFmt += opts.realTimeFmt;
			}
			for (var key in momentMap) {
				velFmt = velFmt.replace(new RegExp(key, "g"), momentMap[key]);
			}
			this.$vel.val(moment(value == "" ? (firebird.date.format(new Date())) : value, velFmt).format(velFmt));

			return this;
		},
		applyValue: function (value) {
			return value;
		},
		getValue: function () {
			return this.$vel.val();
			//if (this.options.vel) {
			//
			//}
			//return this.outFilter(this.instance.val());
		},
		asyncTimer: 0,
		asyncValue: function () {
			var me = this;
			clearTimeout(me.asyncTimer);
			me.asyncTimer = setTimeout(function () {
				try {
					me.setValue(me.instance.val());
					me.instance.trigger("onAsyncValue");
				} catch (e) {
					firebird.info(e);
				}
			}, 0);
		},

		inFilter: function (value) {
			return value;
		},
		outFilter: function (value) {
			return value;
		},
		clear: function () {
			this.instance.val("");
			this.$vel.val("");
			return this;
		}

	});

	module.exports = Firebird.ui.DatePicker;

});